<?php

namespace app\admin\controller;

use app\model\AdminMenuModel;
use app\model\AdminModel;
use app\model\AdminRolesModel;
use app\model\OptionModel;
use app\model\UploadFileModel;
use Shopwwi\LaravelCache\Cache;
use support\Request;
use Webman\Event\Event;

class SystemController
{

    /**
     * 系统设置
     */
    public function setting(Request $request)
    {
        if (is_post()) {

            $post = $request->only(['site_config','upload_config']);

            foreach ($post as $k => $v) {

                $info = OptionModel::where("option_name", $k)->first();

                if (!empty($info)) {
                    //修改
                    OptionModel::where("id", $info['id'])->update(['option_value' => $v]);
                } else {
                    //新增
                    OptionModel::create(['option_name' => $k, 'option_value' => $v]);
                }
            }
            //清理缓存
            Cache::tags('option')->flush();

            return success('操作成功');
        }

        $site_config = get_option_value('site_config', true);
        $upload_config = get_option_value('upload_config', true);

        return view('system/setting', [
            'site_config' => $site_config,
            'upload_config' => $upload_config,
        ]);
    }

    /**
     * 保存系统设置
     */
    public function editSetting(Request $request)
    {
    }

    /**
     * 菜单管理
     */
    public function menu(Request $request)
    {
        return view('system/menu');
    }

    /**
     * 获取菜单列表
     */
    public function getMenuList(Request $request)
    {
        $menuModel = new AdminMenuModel();

        $list = $menuModel->orderBy("sort", "desc")->get();

        return success('ok', $list);
    }

    /**
     * 菜单添加/编辑
     */
    public function editMenu(Request $request)
    {
        $id = $request->input('id', 0);

        $menuModel = new AdminMenuModel();

        if (is_post()) {

            $post = $request->post();
            $post['pid'] = $post['plist_select_nodeId'];

            $where = [
                ['action', '=', $post['action']],
                ['controller', '=', $post['controller']],
                ['app', '=', $post['app']],
            ];

            if ($post['id']) $where[] = ['id', '<>', $post['id']];

            if ($menuModel->where($where)->exists()) {
                return error('路由重复');
            }

            $data = [
                'pid' => $post['pid'],
                'title' => $post['title'],
                'action' => $post['action'],
                'controller' => $post['controller'],
                'app' => $post['app'],
                'icon' => $post['icon'],
                'type' => $post['type'],
                'is_show' => $post['is_show'],
                'sort' => $post['sort'],
            ];

            if ($post['id']) {
                //编辑
                $update = $menuModel->find($post['id']);
                $update->where("id", $post['id'])->update($data);
            } else {
                AdminMenuModel::create($data);
            }

            //清除菜单缓存
            Cache::tags('admin_rules')->flush();

            return success('操作成功');
        }

        $info = [];
        if ($id) {
            $info = $menuModel->find($id)->toArray();
        }

        return view('system/edit_menu', [
            'info' => $info,
            'id' => $id
        ]);
    }

    /**
     * 菜单删除
     */
    public function delMenu(Request $request)
    {
        $id = $request->input('id');

        if (empty($id)) return error("参数错误");

        $menu = AdminMenuModel::find($id);

        if (empty($menu)) {
            return error("数据不存在!");
        }

        $menu->delete();

        return success("操作成功");
    }

    /**
     * 菜单树状下拉选择框接口
     */
    public function getMenuSelect(Request $request)
    {
        $menuModel = new AdminMenuModel();

        $list = $menuModel->orderBy('sort', 'desc')->get(['id', 'pid', 'title'])->toArray();

        $newlist = [];
        foreach ($list as $k => $v) {
            $newlist[$v['id']] = $v;
        }

        $newtree = [];
        $newtree[] = ['id' => 0, 'title' => '顶级菜单', 'pid' => 0];
        foreach ($newlist as $k => $v) {
            if ($v['pid']) {
                $newlist[$v['pid']]['children'][] = &$newlist[$k];
            } else {
                $newtree[] = &$newlist[$k];
            }
        }

        return json(['status' => ['code' => 200, 'message' => 'ok'], 'data' => $newtree]);
    }

    /**
     * 角色管理
     */
    public function roles(Request $request)
    {
        return view('system/roles');
    }

    /**
     * 获取角色列表
     */
    public function getRolesList(Request $request)
    {

        $params = $request->all();

        $rolesModel = new AdminRolesModel();

        $limit = $request->input('limit', 15);

        $list = $rolesModel->where(function ($query) use ($params) {
            if (!empty($params['name'])) {
                $query->where("name", 'like', "{$params['name']}%");
            }
        })->orderBy("id", "asc")->paginate($limit);

        return success('ok', $list->items(), ['count' => $list->total()]);
    }

    /**
     * 添加/编辑 角色
     */
    public function editRoles(Request $request)
    {
        $id = $request->input('id', 0);

        if ($id == 1) {
            return error('无法编辑超级管理员');
        }

        $rolesModel = new AdminRolesModel();

        if (is_post()) {

            $post = $request->post();
            $rules = "";
            if ($post['rules']) {
                foreach ($post['rules'] as $k => $v) {
                    if ($v['nodeId'] && $v['checked'] == "1") {
                        $rules .= $v['nodeId'] . ",";
                    }
                }
            }

            $post['rules'] = trim($rules, ",");

            $data = [
                'name' => $post['name'],
                'rules' => $post['rules']
            ];

            if ($id) {
                //编辑
                $info = $rolesModel->find($id);
                $info->where("id", $id)->update($data);
            } else {
                //添加
                AdminRolesModel::create($data);
            }

            //清除权限菜单
            Cache::tags('admin_rules')->flush();

            return success('操作成功');
        }

        $info = [];
        if ($id) {
            $info = $rolesModel->find($id);
        }

        return view('system/edit_roles', [
            'info' => $info,
            'id' => $id
        ]);
    }

    /**
     * 删除角色
     */
    public function delRoles(Request $request)
    {
        $id = $request->input('id', 0);

        if (empty($id)) return error('参数错误');

        if ($id == 1) return error('无法删除超级管理员');

        $rolesModel = new AdminRolesModel();

        $info = $rolesModel->find($id);

        if (empty($info)) return error('数据不存在');

        $info->delete();

        //清理缓存
        Cache::tags('admin_rules')->flush();

        return success('操作成功');
    }

    /**
     * 获取角色菜单多选框
     */
    public function getRolesMenu(Request $request)
    {

        $rolesModel = new AdminRolesModel();
        $id = $request->input('id', 0);

        $check_ids = [];
        if ($id) {
            //获取选中内容
            $info = $rolesModel->where("id", $id)->value("rules");
            if ($info) {
                $check_ids = explode(",", $info);
            }
        }

        //获取所有菜单
        $menuModel = new AdminMenuModel();
        $list = $menuModel->orderBy("sort", "desc")->get()->toArray();

        $newlist = [];
        foreach ($list as $k => $v) {
            if (in_array($v['id'], $check_ids)) {
                $v['checkArr'] = ['checked' => 1];
            } else {
                $v['checkArr'] = ['checked' => 0];
            }
            $newlist[$v['id']] = $v;
        }

        $newtree = [];
        foreach ($newlist as $k => $v) {
            if ($v['pid']) {
                $newlist[$v['pid']]['children'][] = &$newlist[$k];
            } else {
                $newtree[] = &$newlist[$k];
            }
        }

        return json(['status' => ['code' => 200, 'message' => 'ok'], 'data' => $newtree]);
    }

    /**
     * 管理员管理
     */
    public function admin(Request $request)
    {
        return view('system/admin');
    }

    /**
     * 获取管理员列表
     */
    public function getAdminList(Request $request)
    {

        $params = $request->all();

        $model = new AdminModel();

        $limit = $request->input('limit', 15);

        $list = $model->where(function ($query) use ($params) {
            if (!empty($params['account'])) {
                $query->where("account", 'like', "{$params['account']}%");
            }
        })->orderBy("id", "asc")->paginate($limit);

        $total = $list->total();
        $items = $list->each(function ($item) {
            $item->last_login_time = date('Y-m-d H:i:s', $item->last_login_time);
        });

        return success('ok', $items, ['count' => $total]);
    }

    /**
     * 添加/编辑 管理员
     */
    public function editAdmin(Request $request)
    {
        $id = $request->input('id', 0);

        if ($id == 1) return error('无法编辑admin用户');

        $adminModel = new AdminModel();

        if (is_post()) {

            $post = $request->post();

            if ($post['roles']) {
                $post['roles'] = trim(implode(",", $post['roles']), ",");
            }

            $data = [
                'account' => $post['account'],
                'status' => $post['status'],
                'roles' => $post['roles'],
            ];

            //处理密码
            if (!empty($post['password'])) {
                $data['password'] = get_password($post['password']);
            }

            $where = [
                ['account', '=', $post['account']],
            ];

            if (!empty($id)) $where[] = ['id', '<>', $post['id']];

            if ($adminModel->where($where)->exists()) {
                return error('账号重复');
            }

            if (!empty($id)) {
                //编辑
                $info = $adminModel->find($id);
                $info->where("id", $id)->update($data);
            } else {
                if (empty($data['password'])) {
                    return error('请输入管理员密码!');
                }
                //添加
                $admin = AdminModel::create($data);
                $id = $admin->id;
            }

            //更新管理员缓存
            Event::emit('admin.admin_upd_cache', $id);
            //更新菜单缓存
            Cache::tags('admin_rules')->flush();

            return success('操作成功');
        }

        $info = [];
        if (!empty($id)) {
            $info = $adminModel->find($id);
        }

        //查询角色
        $rolesModel = new AdminRolesModel();
        $roleslist = $rolesModel->get(['id', 'name'])->toArray();

        if ($info['roles']) {
            //处理选中
            $user_roles = array_unique(explode(",", $info['roles']));
            foreach ($roleslist as $k => $v) {
                if (in_array($v['id'], $user_roles)) {
                    $roleslist[$k]['ischeck'] = 'checked';
                }
            }
        }

        return view('system/edit_admin', [
            'roleslist' => $roleslist,
            'info' => $info,
            'id' => $id
        ]);
    }

    /**
     * 修改管理员状态
     */
    public function updAdminStatus(Request $request)
    {
        $id = $request->input('id', 0);
        $checked = $request->input('checked');

        if (!$id || !$checked) {
            return error('参数错误');
        }

        if ($id == 1) return error('无法修改admin');

        if ($checked == 'true') {
            AdminModel::where('id', $id)->update(['status' => 1]);
        } else {
            AdminModel::where('id', $id)->update(['status' => 0]);
        }
        //更新管理员缓存
        Event::emit('admin.admin_upd_cache', $id);

        return success('操作成功');
    }

    /**
     * 删除管理员
     */
    public function delAdmin(Request $request)
    {
        $id = $request->input('id', 0);

        if (empty($id)) return error('参数错误');
        if ($id == 1) return error('无法删除admin用户');

        $adminModel = new AdminModel();

        if (!$adminModel->where("id", $id)->exists()) {
            return error("数据不存在");
        }

        $adminModel->where("id", $id)->delete();

        //更新管理员相关缓存
        Event::emit('admin.admin_upd_cache', $id);
        Cache::tags('admin_rules')->flush();

        return success('操作成功');
    }

    /**
     * 修改密码
     */
    public function editPassword(Request $request)
    {

        if (is_post()) {
            $data = $request->post();

            if (empty($data['password']) || empty($data['confirm_password'])) {
                return error("请输入新密码");
            }

            if ($data['password'] !== $data['confirm_password']) {
                return error("新密码与确认密码不同");
            }

            $admin_id = get_admin_id();
            if ($admin_id == 1) {
                return error('如需修改admin代码可屏蔽此条件后修改!');
            }

            $admin = AdminModel::find($admin_id);

            $admin->password = get_password($data['password']);

            $admin->save();

            //清除登录状态
            $request->session()->set('admin_id', 0);

            return success("修改成功");
        }

        return view('system/edit_password');
    }

    /**
     * 附件上传记录
     */
    public function uploadFile(Request $request){
        return view('system/uploadfile');
    }

    /**
     * 获取附件上传记录列表
     */
    public function getUploadFile(Request $request){
        $params = $request->all();

        $uploadModel = new UploadFileModel();

        $limit = $request->input('limit', 15);

        $list = $uploadModel->select(['id','origin_name','save_name','save_path','url','unique_id','size','mime_type','extension','created_at'])->where(function($query) use ($params){
            // if(!empty($params['name'])){
            //     $query->where("origin_name",'like',"%{$params['name']}%");
            // }
        })->orderBy("id","desc")->paginate($limit);

        $count = $list->total();
        $items = $list->each(function($item,$key){
            $item->size = sprintf("%.3f",$item->size / 1024 / 1024).'M';
            $item->url = get_image_url($item->url);
        });

        return success('ok',$items,['count'=>$count]);
    }

}
